<?php

global $xoopsConfig,$xoopsOption,$xoopsUser,$xoopsTpl;

/**
 * MUST include our module page header
 */
require('header.inc');

session_start();

if (isset($_SESSION['confreg_group'])) {
	$group = unserialize($_SESSION['confreg_group']);
}

if (isset($_SESSION['confreg_users'])) {
	$users = unserialize($_SESSION['confreg_users']);
}

// clean all input
//$cleanPost = ParanoiaCleanByKey($_POST);
$cleanPost = cleanInput($_POST);

$submit = $cleanPost['submit'];

if ($submit == _MD_CONFREG_REGISTER) {
	// if session data already exists, kill it
	if (isset($_SESSION['confreg_group'])) {
		unset($_SESSION['confreg_group']);
		unset($group);
	}

	if (isset($_SESSION['confreg_users'])) {
		unset($_SESSION['confreg_users']);
		unset($users);
	}
}

if (isset($group['conf_id'])) {
	$conf_id = intval($group['conf_id']);
} else {
	$conf_id = intval($cleanPost['conf_id']);
}

if (empty($submit) or empty($conf_id)) {
		redirect_header(XOOPS_URL.'/modules/confreg/',5, 'invalid conference id specified, redirecting to main page');
}
// get configuration data from db
// day_count is number of days of conference
$confHdl = $xoopsDB->query(	'SELECT *, DATEDIFF(DATE(end_date), DATE(start_date)) as day_count' .
                            ' FROM ' . $xoopsDB->prefix('confreg_conferences') .
                            ' WHERE conf_id=' . $conf_id);
$confData = $xoopsDB->fetchArray($confHdl);

if (empty($confData)) {
		redirect_header(XOOPS_URL.'/modules/confreg/',5, 'invalid conference specified, redirecting to main page');
}

// find cost per person per day
$right_now = mktime();
if ($right_now <= strtotime($confData['early_cutoff'])) {
	$confData['cur_cost'] = '$' . money_format('%.2n',floatval($confData['early_cost']));
} else {		
	$confData['cur_cost'] = '$' . money_format('%.2n',floatval($confData['late_cost']));
}	


// verify conference is available and registration is still open
if (($right_now <= strtotime($confData['reg_start'])) or ($right_now >= strtotime($confData['reg_end']))
		or (intval($confData['conf_archived']) <> 0)) {
	require_once XOOPS_ROOT_PATH.'/header.php';	
	echo _MD_CONFREG_CLOSED;
	include XOOPS_ROOT_PATH.'/footer.php';
	exit();
}

// build an array of labels for each day of the conference
for ($i = 0; $i <= intval($confData['day_count']); $i++) {
	$cdates[] = strftime('%a %b %e, %Y', strtotime( $confData['start_date'] . " +" . $i . " days" ));
}

// build an array of distinct start times for workshops that are still open
$tHdl =& $xoopsDB->query('SELECT DISTINCT start_date, end_date' .
						 ' FROM ' . $xoopsDB->prefix('confreg_extras') .
						 ' WHERE ((conf_id=' . $conf_id . ')' . 
						 ' AND (start_date <> end_date)' .
						 ' AND (full <> 1))' .
						 ' ORDER BY start_date');

if (!$tHdl) {
	echo '<p>Error occured reading workshops!';
	break;
}

// build array of labels for each start/stop time, and workshops for that time
while ($result = $xoopsDB->fetchArray($tHdl)) {
	$wtimes[] = strftime('%a %b %e, %Y, %I:%M %p to ', strtotime($result['start_date'])) .
				strftime('%I:%M %p', strtotime($result['end_date']));
	if (isset($users)) {
		$workshops[] = getWorkshops($conf_id,$result['start_date'],$users);
	} else {
		$workshops[] = getWorkshops($conf_id,$result['start_date'],null);
	}	
}

if (isset($users)) {
	$extras = getExtras($conf_id,$users);
} else {
	$extras = getExtras($conf_id,null);
}

$extraNames = getExtraNames($conf_id);

// cute trick to allow any expression that returns a
// boolean to be used in the case statements. Any case
// that evaluates to TRUE will be executed.
switch (TRUE) {

// registration intro, get company name
case ($submit == _MD_CONFREG_REGISTER):

	//template for beginning process
	$xoopsOption['template_main'] = 'startregistration.tpl';	
	//Xoops main header file
	require_once XOOPS_ROOT_PATH."/header.php";	
	// put the conference id in the group data session
	$group['conf_id'] = $conf_id;
	$group['user_count'] = 0;
	$group['sess_time'] = mktime();
	$_SESSION['confreg_group'] = serialize($group);
	
	//assign conference config data to the template
	$xoopsTpl->assign('confData',$confData);
	break;

// initial register attendees page
case ($submit == _MD_CONFREG_BTN_REGISTER_ATTENDEES):
	// first verify required fields from company info form were submitted
	$missingFields = verifyKeys($cleanPost,array('company'));
	if (!empty($missingFields)) {
		// handle missing fields
		$xoopsOption['template_main'] = 'startregistration.tpl';	
		// need the state names in this template
		require_once XOOPS_ROOT_PATH.'/header.php';	
		$xoopsTpl->assign('confData',$confData);
		$xoopsTpl->assign('missingFields',$missingFields);
		break;
	}

	$xoopsOption['template_main'] = 'getusers.tpl';	
	require_once XOOPS_ROOT_PATH."/header.php";

	// add company name to group data
	$group['company'] = $cleanPost['company'];
	$group['user_count'] = 0;
	// save the group data
	$_SESSION['confreg_group'] = serialize($group);

	$xoopsTpl->assign('group',$group);
	$xoopsTpl->assign('confData',$confData);
	$xoopsTpl->assign('dates', $cdates);
	$xoopsTpl->assign('days', $wtimes);
	$xoopsTpl->assign('workshops', $workshops);
	$xoopsTpl->assign('extras', $extras);

	break;

case ($submit === 'Add Another Person'):
	// add new user from register attendees page

	$missingFields = verifyKeys($cleanPost,array("fname","lname"));
	$badData = validateUserDays($cleanPost,$cdates);

	if ((!empty($missingFields)) or ($badData > 0)) {
		$xoopsOption['template_main'] = 'getusers.tpl';	
		require_once XOOPS_ROOT_PATH."/header.php";	
		// handle missing fields
		$xoopsTpl->assign('missingFields',$missingFields);
		$xoopsTpl->assign('badData',$badData);
		$xoopsTpl->assign('users', $users);
 		$xoopsTpl->assign('group', $group);
 		$xoopsTpl->assign('dates', $cdates);
 		$xoopsTpl->assign('days', $wtimes);
 		$xoopsTpl->assign('workshops', $workshops);
 		$xoopsTpl->assign('extras', $extras);
 		$xoopsTpl->assign('confData',$confData);
		// break from switch statement
		break;
	}

	$xoopsOption['template_main'] = 'getusers.tpl';	
	require_once XOOPS_ROOT_PATH."/header.php";	

	// keep from accidentally adding same user on a browser reload
	if (!isset($users[intval($cleanPost['user_id'])]['last_name'])) {
		$u_id = $group['user_count']++;
		$users[$u_id]=userData($cleanPost, $u_id, $confData, $cdates, $extraNames);
	}

	$group['total_cost'] = calcTotalCost($users);
	$group['total_cost_disp'] = '$' . money_format('%.2n',$group['total_cost']);
	
 	$_SESSION['confreg_group'] = serialize($group);
 	$_SESSION['confreg_users'] = serialize($users);

	$xoopsTpl->assign('group', $group);
	$xoopsTpl->assign('users', $users);
	$xoopsTpl->assign('dates', $cdates);
	$xoopsTpl->assign('days', $wtimes);
	$xoopsTpl->assign('workshops', $workshops);
	$xoopsTpl->assign('extras',$extras);
	$xoopsTpl->assign('confData',$confData);

	break;

case ($submit === 'Add More People'):
	// Add more people comes from checkout screen
	// group info may be entered. Don't worry about
	// missing fields as they have to go back to checkout
	// screen.
	
	$xoopsOption['template_main'] = 'getusers.tpl';	
	require_once XOOPS_ROOT_PATH."/header.php";	

	// save any group data entered on checkout screen
	if (isset($cleanPost['company'])) {
		$group['company'] = $cleanPost['company'];
	}
	if (isset($cleanPost['billfname'])) {
		$group['bill_fname'] = $cleanPost['billfname'];
	}
	if (isset($cleanPost['billlname'])) {
		$group['bill_lname'] = $cleanPost['billlname'];
	}
	if (isset($cleanPost['phone'])) {
		$group['phone'] = $cleanPost['phone'];
	}
	if (isset($cleanPost['paytype'])) {
		$group['paytype'] = $cleanPost['paytype'];
	}
	if (isset($cleanPost['billaddress'])) {
		$group['billaddress1'] = $cleanPost['billaddress'];
	}
	if (isset($cleanPost['billcity'])) {
		$group['billcity'] = $cleanPost['billcity'];
	}
	if (isset($cleanPost['billstate'])) {
		$group['billstate'] = $cleanPost['billstate'];
	}
	if (isset($cleanPost['billzip'])) {
		$group['billzip'] = $cleanPost['billzip'];
	}
	if (isset($cleanPost['confirmemail'])) {
		$group['confirm_email'] = $cleanPost['confirmemail'];
	}

	$group['total_cost'] = calcTotalCost($users);
	$group['total_cost_disp'] = '$' . money_format('%.2n',$group['total_cost']);
	
 	$_SESSION['confreg_group'] = serialize($group);
 	$_SESSION['confreg_users'] = serialize($users);

	$xoopsTpl->assign('group', $group);
	$xoopsTpl->assign('users', $users);
	$xoopsTpl->assign('dates', $cdates);
	$xoopsTpl->assign('days', $wtimes);
	$xoopsTpl->assign('workshops', $workshops);
	$xoopsTpl->assign('extras',$extras);
	$xoopsTpl->assign('confData',$confData);

	break;

case (strtolower(substr($submit,0,4)) === "edit"):
	// Edit user comes from checkout screen
	// group info may be entered. Don't worry about
	// missing fields as they have to go back to checkout
	// screen.
	
	$xoopsOption['template_main'] = 'edit_user.tpl';	
	require_once XOOPS_ROOT_PATH."/header.php";	

	// save any group data entered on checkout screen
	if (isset($cleanPost['company'])) {
		$group['company'] = $cleanPost['company'];
	}
	if (isset($cleanPost['billfname'])) {
		$group['bill_fname'] = $cleanPost['billfname'];
	}
	if (isset($cleanPost['billlname'])) {
		$group['bill_lname'] = $cleanPost['billlname'];
	}
	if (isset($cleanPost['phone'])) {
		$group['phone'] = $cleanPost['phone'];
	}
	if (isset($cleanPost['paytype'])) {
		$group['paytype'] = $cleanPost['paytype'];
	}
	if (isset($cleanPost['billaddress'])) {
		$group['billaddress1'] = $cleanPost['billaddress'];
	}
	if (isset($cleanPost['billcity'])) {
		$group['billcity'] = $cleanPost['billcity'];
	}
	if (isset($cleanPost['billstate'])) {
		$group['billstate'] = $cleanPost['billstate'];
	}
	if (isset($cleanPost['billzip'])) {
		$group['billzip'] = $cleanPost['billzip'];
	}
	if (isset($cleanPost['confirmemail'])) {
		$group['confirm_email'] = $cleanPost['confirmemail'];
	}

	$group['total_cost'] = calcTotalCost($users);
	$group['total_cost_disp'] = '$' . money_format('%.2n',$group['total_cost']);
	
 	$_SESSION['confreg_group'] = serialize($group);
 	$_SESSION['confreg_users'] = serialize($users);

	$u_id = intval(str_ireplace('edit ', '', $submit));

	// selected workshops indexed by extra_id
	$sel_extra = null;
	foreach ($users[$u_id]['extra'] as $e_id) {
		$sel_extra[$e_id] = 1;
	}

	// see if none should be selected for workshops
	$work_sel = null;
	foreach ($workshops as $day => $day_shops) {
		$selected = false;
		foreach ($day_shops as $this_shop) {
			if (isset($sel_extra[$this_shop['extra_id']])) {
				$selected = true;
			}
		}
		if (!$selected) {
			$work_sel[$day] = 1;
		}
	}

	$xoopsTpl->assign('u_id', $u_id);
	$xoopsTpl->assign('thisUser', $users[$u_id]);
	$xoopsTpl->assign('sel_extra', $sel_extra);
	$xoopsTpl->assign('work_sel', $work_sel);
	$xoopsTpl->assign('group', $group);
	$xoopsTpl->assign('users', $users);
	$xoopsTpl->assign('dates', $cdates);
	$xoopsTpl->assign('days', $wtimes);
	$xoopsTpl->assign('workshops', $workshops);
	$xoopsTpl->assign('extras',$extras);
	$xoopsTpl->assign('confData',$confData);

	break;

// start checkout process by confirming data
case ($submit === "Save and Return to Checkout"):

	if ((!empty($cleanPost['fname'])) || (!empty($cleanPost['lname']))) {
		$missingFields = verifyKeys($cleanPost,array("fname","lname"));
		$badData = validateUserDays($cleanPost,$cdates);
	
		if ((!empty($missingFields)) or ($badData > 0)) {
			// handle missing fields
			$xoopsOption['template_main'] = 'getusers.tpl';	
			require_once XOOPS_ROOT_PATH."/header.php";	
			$xoopsTpl->assign('missingFields',$missingFields);
			$xoopsTpl->assign('badData',$badData);
			$xoopsTpl->assign('users', $users);
			$xoopsTpl->assign('group', $group);
			$xoopsTpl->assign('dates', $cdates);
			$xoopsTpl->assign('days', $wtimes);
			$xoopsTpl->assign('workshops', $workshops);
			$xoopsTpl->assign('extras', $extras);
			$xoopsTpl->assign('confData',$confData);
			// break from switch statement
			break;
		} else {
			$u_id = $cleanPost['user_id'];
			$users[$u_id]=userData($cleanPost, $u_id, $confData, $cdates, $extraNames);
		}
	}

	$xoopsOption['template_main'] = 'confirmreg.tpl';	
	require_once XOOPS_ROOT_PATH."/header.php";
	include CONFREG_PATH . '/language/' . $xoopsConfig['language'] . '/states.php';

	$group['total_cost'] = calcTotalCost($users);
	$group['total_cost_disp'] = '$' . money_format('%.2n',$group['total_cost']);

 	$_SESSION['confreg_group'] = serialize($group);
 	$_SESSION['confreg_users'] = serialize($users);

	$xoopsTpl->assign('group', $group);
	$xoopsTpl->assign('users', $users);
	$xoopsTpl->assign('confData',$confData);
	break;


// start checkout process by confirming data
case ($submit === "Checkout"):

	if ((!empty($cleanPost['fname'])) || (!empty($cleanPost['lname']))) {
		$missingFields = verifyKeys($cleanPost,array("fname","lname"));
		$badData = validateUserDays($cleanPost,$cdates);
	
		if ((!empty($missingFields)) or ($badData > 0)) {
			// handle missing fields
			$xoopsOption['template_main'] = 'getusers.tpl';	
			require_once XOOPS_ROOT_PATH."/header.php";	
			$xoopsTpl->assign('missingFields',$missingFields);
			$xoopsTpl->assign('badData',$badData);
			$xoopsTpl->assign('users', $users);
			$xoopsTpl->assign('group', $group);
			$xoopsTpl->assign('dates', $cdates);
			$xoopsTpl->assign('days', $wtimes);
			$xoopsTpl->assign('workshops', $workshops);
			$xoopsTpl->assign('extras', $extras);
			$xoopsTpl->assign('confData',$confData);
			// break from switch statement
			break;
		} else {
			// keep from accidentally adding same user on a browser reload
			if (!isset($users[intval($cleanPost['user_id'])]['last_name'])) {
				$u_id = $group['user_count']++;
				$users[$u_id]=userData($cleanPost, $u_id, $confData, $cdates, $extraNames);
			}
		}
	}

	$xoopsOption['template_main'] = 'confirmreg.tpl';	
	require_once XOOPS_ROOT_PATH."/header.php";
	include CONFREG_PATH . '/language/' . $xoopsConfig['language'] . '/states.php';

	$group['total_cost'] = calcTotalCost($users);
	$group['total_cost_disp'] = '$' . money_format('%.2n',$group['total_cost']);

 	$_SESSION['confreg_group'] = serialize($group);
 	$_SESSION['confreg_users'] = serialize($users);

	$xoopsTpl->assign('group', $group);
	$xoopsTpl->assign('users', $users);
	$xoopsTpl->assign('confData',$confData);
	break;

// Finished! Write the data to the db.
case ($submit === 'Finish'):

	// first verify required fields from previous form were submitted
	$missingFields = verifyKeys($cleanPost,array("company","billfname","billlname","paytype"));
	if (!empty($missingFields)) {
		$xoopsOption['template_main'] = 'confirmreg.tpl';	
		require_once XOOPS_ROOT_PATH."/header.php";	
		// handle missing fields
		$xoopsTpl->assign('missingFields',$missingFields);
		$xoopsTpl->assign('users', $users);
 		$xoopsTpl->assign('group', $group);
 		$xoopsTpl->assign('confData',$confData);
		// break from switch statement
		break;
	}

	$xoopsOption['template_main'] = 'confirmpay.tpl';	
	require_once XOOPS_ROOT_PATH."/header.php";	

	$group['company'] = $cleanPost['company'];
	$group['bill_fname'] = $cleanPost['billfname'];
	$group['bill_lname'] = $cleanPost['billlname'];
	$group['phone'] = $cleanPost['phone'];
	$group['paytype'] = $cleanPost['paytype'];
	$group['billaddress1'] = $cleanPost['billaddress'];
	$group['billcity'] = $cleanPost['billcity'];
	$group['billstate'] = $cleanPost['billstate'];
	$group['billzip'] = $cleanPost['billzip'];
	$group['confirm_email'] = $cleanPost['confirmemail'];
	$group['total_cost'] = calcTotalCost($users);
	$group['total_cost_disp'] = '$' . money_format('%.2n',$group['total_cost']);

	$group_insert = 'INSERT INTO ' . $xoopsDB->prefix('confreg_groups') .
					' SET conf_id=' . intval($conf_id) .
 					', company=' . $xoopsDB->quoteString(substr($group['company'],0,128)) .
					', phone=' . $xoopsDB->quoteString(substr($group['phone'],0,25)) .
					', paytype=' . $xoopsDB->quoteString(substr($group['paytype'],0,15)) .
					', bill_fname=' . $xoopsDB->quoteString(substr($group['bill_fname'],0,45)) .
 					', bill_lname=' . $xoopsDB->quoteString(substr($group['bill_lname'],0,45)) .
 					', billaddress1=' . $xoopsDB->quoteString(substr($group['billaddress1'],0,128)) .
 					', confirm_email=' . $xoopsDB->quoteString(substr($group['confirm_email'],0,128)) .
 					', billcity=' . $xoopsDB->quoteString(substr($cleanPost['billcity'],0,64)) .
 					', billstate=' . $xoopsDB->quoteString(substr($cleanPost['billstate'],0,24)) .
 					', billzip=' . $xoopsDB->quoteString(substr($cleanPost['billzip'],0,15)) .
 					', total_cost=' . floatval($cleanPost['total_cost']);
	$groupHdl = $xoopsDB->query($group_insert);
	$group_id = $xoopsDB->getInsertId();
	$group['confirmation'] = $confData['confirm_offset'] . str_pad($group_id, 4, "0", STR_PAD_LEFT);
	$group['count'] = count($users);

	foreach ($users as $thisUser) {
		$attending = str_ireplace('<br />','; ',$thisUser['attend_desc']);
		
		$user_insert = 	'INSERT INTO ' . $xoopsDB->prefix('confreg_people') .
		' SET group_id=' . intval($group_id) .
		', first_name=' . $xoopsDB->quoteString(substr($thisUser['first_name'],0,45)) .
		', last_name=' . $xoopsDB->quoteString(substr($thisUser['last_name'],0,45)) .
		', tmc_num=' . $xoopsDB->quoteString(substr($thisUser['member_num'],0,24)) .
		', email=' . $xoopsDB->quoteString(substr($thisUser['email'],0,128)) .
		', days_attending=' . $xoopsDB->quoteString(substr($attending,0,48)) .
		', cost=' . floatval($thisUser['cost']);

		$userHdl = $xoopsDB->query($user_insert);
		$user_id = $xoopsDB->getInsertId();

		// record the extras options
		foreach( $thisUser['extra'] as $thisExtra) {
			$e_insert = 'INSERT INTO ' . $xoopsDB->prefix('confreg_extra_reservations') .
			' SET extra_id=' . intval($thisExtra) .
			', user_id=' . intval($user_id);
			$eHdl = $xoopsDB->query($e_insert);
			$res_id = $xoopsDB->getInsertId();
		}			
	}

 	$_SESSION['confreg_group'] = serialize($group);
 	$_SESSION['confreg_users'] = serialize($users);

	if (!empty($group['confirm_email'])) {
		mailConfirmation($confData,$group,$users);
	}

	$thisUser['attend_desc'] = trim(str_ireplace('<br />','; ',$thisUser['attend_desc']));
	$thisUser['extras_desc'] = trim(str_ireplace('<br />','; ',$thisUser['extras_desc']));

	$xoopsTpl->assign('group', $group);
	$xoopsTpl->assign('users', $users);
	$xoopsTpl->assign('confData',$confData);

	break;

// nothing else matched, error!
default:
	//Xoops main header file
	require_once XOOPS_ROOT_PATH."/header.php";	
	echo '<p>' . _MD_CONFREG_ERR_1 . '<br />' . _MD_CONFREG_ERR_2 . '<p>';
}

// Xoops page footer
include XOOPS_ROOT_PATH."/footer.php";


/*
 * This file was generated by XBS ModGen, (c) 2006 A Kitson, UK. See http://xoobs.net
 * ModGen is a Module Code Generator for the Xoops CMS.  See http://xoops.org
 */
?>
